package mybook.controller;

import java.util.List;
import jgo.Context;
import mybook.model.Book;
import mybook.service.BookService;
import com.alibaba.fastjson.JSON;

public class BookController {
    public static final BookController instance = new BookController();

    public BookController() {
    }

    public void handleGetAllBooks(Context ctx) {
        List<Book> books = BookService.instance.getAllBooks();
        ctx.json(books);
    }

    public void handleGetBook(Context ctx) {
        int id = Integer.parseInt(ctx.getPath().split("/")[2]);
        Book book = BookService.instance.getBookById(id);
        if (book != null) {
            ctx.json(book);
        } else {
            ctx.status(404).json("Book not found");
        }
    }

    public void handleAddBook(Context ctx) {
        Book book = JSON.parseObject(ctx.body(), Book.class);
        BookService.instance.addBook(book);
        ctx.status(201).json("Book added successfully");
    }

    public void handleUpdateBook(Context ctx) {
        int id = Integer.parseInt(ctx.getPath().split("/")[2]);
        Book book = JSON.parseObject(ctx.body(), Book.class);
        book.id = id;
        BookService.instance.updateBook(book);
        ctx.json("Book updated successfully");
    }

    public void handleDeleteBook(Context ctx) {
        int id = Integer.parseInt(ctx.getPath().split("/")[2]);
        BookService.instance.deleteBook(id);
        ctx.json("Book deleted successfully");
    }
}